<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件功能测试 - Cloud-DMS</title>
    <!-- 引入 Layui CSS -->
    <link rel="stylesheet" href="https://unpkg.com/layui@2.7.6/dist/css/layui.css">
    <style>
        body {
            background: #f5f5f5;
            font-family: 'Microsoft YaHei', sans-serif;
        }

        .test-container {
            max-width: 1000px;
            margin: 20px auto;
            padding: 20px;
        }

        .test-card {
            background: white;
            border-radius: 8px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .test-card h3 {
            margin: 0 0 20px 0;
            color: #333;
            border-bottom: 2px solid #1E9FFF;
            padding-bottom: 10px;
        }

        .upload-area {
            border: 2px dashed #d9d9d9;
            border-radius: 6px;
            padding: 40px;
            text-align: center;
            background: #fafafa;
            transition: border-color 0.3s;
            cursor: pointer;
        }

        .upload-area:hover {
            border-color: #1E9FFF;
        }

        .upload-area.dragover {
            border-color: #1E9FFF;
            background: #f0f8ff;
        }

        .upload-icon {
            font-size: 48px;
            color: #999;
            margin-bottom: 16px;
        }

        .progress-container {
            margin-top: 20px;
            display: none;
        }

        .file-list {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #e6e6e6;
            border-radius: 4px;
            padding: 10px;
        }

        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #f0f0f0;
        }

        .file-item:last-child {
            border-bottom: none;
        }

        .file-info {
            flex: 1;
        }

        .file-name {
            font-weight: bold;
            color: #333;
        }

        .file-meta {
            font-size: 12px;
            color: #666;
            margin-top: 4px;
        }

        .file-actions {
            display: flex;
            gap: 8px;
        }

        .test-section {
            margin-bottom: 30px;
        }

        .result-area {
            background: #f8f8f8;
            border: 1px solid #e6e6e6;
            border-radius: 4px;
            padding: 15px;
            margin-top: 15px;
            max-height: 200px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 12px;
        }

        .status-success {
            color: #52c41a;
        }

        .status-error {
            color: #ff4d4f;
        }

        .status-warning {
            color: #faad14;
        }
    </style>
</head>
<body>
<div class="test-container">
    <!-- 页面标题 -->
    <div class="test-card">
        <h2>
            <i class="layui-icon layui-icon-file"></i>
            文件功能测试页面
        </h2>
        <p>测试安全加密模块和网络传输模块的核心功能</p>
    </div>

    <!-- 文件上传测试 -->
    <div class="test-card">
        <h3>
            <i class="layui-icon layui-icon-upload"></i>
            文件上传测试
        </h3>

        <div class="upload-area" id="uploadArea">
            <div class="upload-icon">
                <i class="layui-icon layui-icon-upload-drag"></i>
            </div>
            <p>点击选择文件或拖拽文件到此区域</p>
            <p style="color: #999; font-size: 12px;">
                支持格式: jpg, png, pdf, doc, docx, xls, xlsx, txt, zip 等<br>
                最大文件大小: 50MB
            </p>
        </div>

        <input type="file" id="fileInput" style="display: none;" multiple>

        <div class="progress-container" id="progressContainer">
            <div class="layui-progress" lay-showPercent="true">
                <div class="layui-progress-bar" id="progressBar" lay-percent="0%"></div>
            </div>
        </div>

        <div class="result-area" id="uploadResult"></div>
    </div>

    <!-- 已上传文件列表 -->
    <div class="test-card">
        <h3>
            <i class="layui-icon layui-icon-list"></i>
            已上传文件列表
        </h3>

        <div class="layui-form">
            <button type="button" class="layui-btn layui-btn-sm" onclick="refreshFileList()">
                <i class="layui-icon layui-icon-refresh"></i> 刷新列表
            </button>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" onclick="getStorageInfo()">
                <i class="layui-icon layui-icon-chart"></i> 存储信息
            </button>
        </div>

        <div class="file-list" id="fileList">
            <div style="text-align: center; color: #999; padding: 20px;">
                暂无文件，请先上传文件
            </div>
        </div>
    </div>

    <!-- 功能测试区域 -->
    <div class="test-card">
        <h3>
            <i class="layui-icon layui-icon-test"></i>
            功能测试
        </h3>

        <div class="test-section">
            <h4>加密测试</h4>
            <div class="layui-form layui-form-pane">
                <div class="layui-form-item">
                    <label class="layui-form-label">文件名</label>
                    <div class="layui-input-block">
                        <input type="text" id="encryptTestFile" placeholder="输入文件名测试是否需要加密" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button type="button" class="layui-btn" onclick="testEncryption()">测试加密需求</button>
                    </div>
                </div>
            </div>
            <div class="result-area" id="encryptResult"></div>
        </div>

        <div class="test-section">
            <h4>文件完整性验证</h4>
            <div class="layui-form layui-form-pane">
                <div class="layui-form-item">
                    <label class="layui-form-label">文件ID</label>
                    <div class="layui-input-inline">
                        <input type="text" id="verifyFileId" placeholder="文件ID" class="layui-input">
                    </div>
                    <label class="layui-form-label">MD5值</label>
                    <div class="layui-input-inline">
                        <input type="text" id="verifyMd5" placeholder="期望的MD5值" class="layui-input">
                    </div>
                    <div class="layui-input-inline">
                        <button type="button" class="layui-btn" onclick="verifyFile()">验证完整性</button>
                    </div>
                </div>
            </div>
            <div class="result-area" id="verifyResult"></div>
        </div>
    </div>

    <!-- 系统状态 -->
    <div class="test-card">
        <h3>
            <i class="layui-icon layui-icon-chart"></i>
            系统状态
        </h3>

        <div class="layui-row layui-col-space15">
            <div class="layui-col-md6">
                <button type="button" class="layui-btn layui-btn-fluid" onclick="checkSystemStatus()">
                    <i class="layui-icon layui-icon-survey"></i> 检查系统状态
                </button>
            </div>
            <div class="layui-col-md6">
                <button type="button" class="layui-btn layui-btn-normal layui-btn-fluid" onclick="getStorageInfo()">
                    <i class="layui-icon layui-icon-chart-screen"></i> 获取存储信息
                </button>
            </div>
        </div>

        <div class="result-area" id="systemResult"></div>
    </div>
</div>

<!-- 引入 Layui JS -->
<script src="https://unpkg.com/layui@2.7.6/dist/layui.js"></script>
<script>
    layui.use(['layer', 'upload', 'element'], function(){
        var layer = layui.layer;
        var upload = layui.upload;
        var element = layui.element;

        // 模拟文件列表
        var uploadedFiles = [];

        // 文件上传
        var uploadInst = upload.render({
            elem: '#uploadArea',
            url: '/api/files/upload',
            accept: 'file',
            multiple: true,
            drag: true,
            data: {
                userId: 1
            },
            progress: function(n, elem, e){
                element.progress('progressBar', n + '%');
                document.getElementById('progressContainer').style.display = 'block';
            },
            done: function(res, index, upload){
                document.getElementById('progressContainer').style.display = 'none';

                if(res.success) {
                    logResult('uploadResult', 'SUCCESS: ' + res.message, 'success');
                    logResult('uploadResult', 'File Info: ' + JSON.stringify(res.data, null, 2), 'success');

                    // 添加到文件列表
                    uploadedFiles.push(res.data);
                    updateFileList();

                    layer.msg('上传成功!', {icon: 1});
                } else {
                    logResult('uploadResult', 'ERROR: ' + res.message, 'error');
                    layer.msg('上传失败: ' + res.message, {icon: 2});
                }
            },
            error: function(index, upload){
                document.getElementById('progressContainer').style.display = 'none';
                logResult('uploadResult', 'UPLOAD ERROR: 网络异常或服务器错误', 'error');
                layer.msg('上传异常!', {icon: 2});
            }
        });

        // 全局函数定义
        window.testEncryption = function() {
            var fileName = document.getElementById('encryptTestFile').value;
            if (!fileName) {
                layer.msg('请输入文件名', {icon: 2});
                return;
            }

            // 模拟加密测试
            var needsEncryption = checkFileNeedsEncryption(fileName);
            var result = `文件: ${fileName}\n需要加密: ${needsEncryption ? '是' : '否'}`;

            logResult('encryptResult', result, needsEncryption ? 'warning' : 'success');
        };

        window.verifyFile = function() {
            var fileId = document.getElementById('verifyFileId').value;
            var md5 = document.getElementById('verifyMd5').value;

            if (!fileId || !md5) {
                layer.msg('请输入文件ID和MD5值', {icon: 2});
                return;
            }

            fetch(`/api/files/verify/${fileId}?expectedMd5=${md5}`, {
                method: 'POST'
            })
                .then(response => response.json())
                .then(data => {
                    var result = `验证结果: ${data.valid ? '通过' : '失败'}\n消息: ${data.message}`;
                    logResult('verifyResult', result, data.valid ? 'success' : 'error');
                })
                .catch(error => {
                    logResult('verifyResult', 'ERROR: ' + error.message, 'error');
                });
        };

        window.checkSystemStatus = function() {
            fetch('/api/status')
                .then(response => response.json())
                .then(data => {
                    var result = `系统状态: ${data.status}\n版本: ${data.version}\n时间: ${data.timestamp}\n`;
                    result += '\n模块状态:\n';
                    for (var key in data.modules) {
                        result += `  ${key}: ${data.modules[key] ? '正常' : '异常'}\n`;
                    }
                    logResult('systemResult', result, 'success');
                })
                .catch(error => {
                    logResult('systemResult', 'ERROR: ' + error.message, 'error');
                });
        };

        window.getStorageInfo = function() {
            fetch('/api/files/storage/info')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        var info = data.data;
                        var result = `存储信息:\n`;
                        result += `总空间: ${formatBytes(info.totalSpace)}\n`;
                        result += `已用空间: ${formatBytes(info.usedSpace)}\n`;
                        result += `可用空间: ${formatBytes(info.freeSpace)}\n`;
                        result += `文件总数: ${info.fileCount}\n`;
                        result += `加密文件数: ${info.encryptedFileCount}`;
                        logResult('systemResult', result, 'success');
                    }
                })
                .catch(error => {
                    logResult('systemResult', 'ERROR: ' + error.message, 'error');
                });
        };

        window.refreshFileList = function() {
            updateFileList();
            layer.msg('列表已刷新', {icon: 1});
        };

        // 下载文件
        window.downloadFile = function(storedName) {
            window.open(`/api/files/download/${storedName}`, '_blank');
        };

        // 删除文件
        window.deleteFile = function(index) {
            layer.confirm('确定要删除这个文件吗？', {icon: 3}, function(layerIndex){
                uploadedFiles.splice(index, 1);
                updateFileList();
                layer.close(layerIndex);
                layer.msg('文件已删除', {icon: 1});
            });
        };

        // 辅助函数
        function logResult(elementId, message, type) {
            var element = document.getElementById(elementId);
            var className = type === 'success' ? 'status-success' :
                type === 'error' ? 'status-error' : 'status-warning';

            var timestamp = new Date().toLocaleTimeString();
            element.innerHTML += `<div class="${className}">[${timestamp}] ${message}</div>`;
            element.scrollTop = element.scrollHeight;
        }

        function checkFileNeedsEncryption(fileName) {
            var encryptExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx'];
            var ext = fileName.split('.').pop().toLowerCase();
            return encryptExtensions.includes(ext);
        }

        function updateFileList() {
            var listElement = document.getElementById('fileList');

            if (uploadedFiles.length === 0) {
                listElement.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;">暂无文件，请先上传文件</div>';
                return;
            }

            var html = '';
            uploadedFiles.forEach((file, index) => {
                html += `
                        <div class="file-item">
                            <div class="file-info">
                                <div class="file-name">${file.originalName}</div>
                                <div class="file-meta">
                                    大小: ${formatBytes(file.fileSize)} |
                                    类型: ${file.contentType || 'unknown'} |
                                    ${file.encrypted ? '已加密' : '未加密'} |
                                    MD5: ${file.fileHash || 'N/A'}
                                </div>
                            </div>
                            <div class="file-actions">
                                <button class="layui-btn layui-btn-sm" onclick="downloadFile('${file.storedName}')">
                                    <i class="layui-icon layui-icon-download-circle"></i>
                                </button>
                                <button class="layui-btn layui-btn-sm layui-btn-danger" onclick="deleteFile(${index})">
                                    <i class="layui-icon layui-icon-delete"></i>
                                </button>
                            </div>
                        </div>
                    `;
            });

            listElement.innerHTML = html;
        }

        function formatBytes(bytes) {
            if (bytes === 0) return '0 Bytes';
            var k = 1024;
            var sizes = ['Bytes', 'KB', 'MB', 'GB'];
            var i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
    });
</script>
</body>
</html>